<template>
  <div class="experience-container">
    <el-card class="experience-card" shadow="hover">
      <div class="header">
        <div class="title-section">
          <h2 class="page-title">
            <el-icon class="title-icon"><Document /></el-icon>
            项目经验总结
            <el-tag v-if="props.projectData.project_name" type="primary" size="small" style="margin-left: 10px;">
              {{ props.projectData.project_name }}
            </el-tag>
          </h2>
          <p class="description">
            项目结束后的经验教训归档与知识管理
            <span v-if="props.projectData.project_id" style="color: #e6a23c; font-weight: 500;">
              (项目编号: {{ props.projectData.project_id }})
            </span>
          </p>
        </div>
        <div class="header-actions">
          <el-button v-if="canAdd" type="primary" @click="openDialog()" class="create-btn">
            <el-icon><Plus /></el-icon>
            添加总结
          </el-button>
          <el-button type="primary" @click="refreshData" class="refresh-btn" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
        </div>
      </div>

      <!-- 项目选择 -->
      <div class="project-selector" v-if="!props.projectData.project_id">
        <el-select v-model="selectedProject" placeholder="选择项目" style="width: 300px" @change="handleProjectChange">
          <el-option label="全部项目" value="all" />
          <el-option 
            v-for="project in projectList" 
            :key="project.project_id" 
            :label="project.project_name" 
            :value="project.project_id" 
          />
        </el-select>
      </div>

      <!-- 筛选区域 -->
      <div class="filter-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索涉及方面、经验总结..."
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="filterAspect" placeholder="涉及方面" clearable>
          <el-option 
            v-for="aspect in aspectOptions" 
            :key="aspect" 
            :label="aspect" 
            :value="aspect" 
          />
        </el-select>
        <el-date-picker
          v-model="filterDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          clearable
        />
      </div>

      <!-- 经验总结列表 -->
      <el-table
        :data="paginatedExperienceList"
        stripe
        border
        class="experience-table"
        v-loading="loading"
        empty-text="暂无经验总结"
      >
        <el-table-column prop="aspect" label="涉及方面" min-width="150" />
        <el-table-column prop="project_id" label="所属项目" width="120" />
        <el-table-column prop="discovery_process" label="问题过程" min-width="200" show-overflow-tooltip />
        <el-table-column prop="summary" label="经验总结" min-width="250" show-overflow-tooltip />
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="viewDetail(scope.row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button v-if="hasPermission" size="small" type="warning" @click="openDialog(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button v-if="hasPermission" size="small" type="danger" @click="handleDelete(scope.row.id)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-section" v-if="filteredExperienceList.length > 0">
        <el-pagination
          :current-page="pagination.page"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredExperienceList.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 经验总结统计 -->
      <div class="experience-stats">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ experienceStats.total }}</div>
                <div class="stat-label">总总结数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ experienceStats.aspects }}</div>
                <div class="stat-label">涉及方面数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ experienceStats.projects }}</div>
                <div class="stat-label">涉及项目数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ experienceStats.thisMonth }}</div>
                <div class="stat-label">本月总结</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 经验总结创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '编辑经验总结' : '添加经验总结'"
      width="800px"
      align-center
    >
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属项目" prop="project_id">
              <el-select v-model="form.project_id" placeholder="请选择项目" style="width: 100%" :disabled="!!props.projectData.project_id">
                <el-option 
                  v-for="project in projectList" 
                  :key="project.project_id" 
                  :label="project.project_name" 
                  :value="project.project_id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="涉及方面" prop="aspect">
              <el-select 
                v-model="form.aspect" 
                placeholder="请选择或输入涉及方面" 
                style="width: 100%"
                filterable
                allow-create
                default-first-option
              >
                <el-option 
                  v-for="aspect in predefinedAspects" 
                  :key="aspect" 
                  :label="aspect" 
                  :value="aspect"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="问题过程" prop="discovery_process">
          <el-input v-model="form.discovery_process" type="textarea" :rows="4" placeholder="请详细描述问题的发现过程、背景和原因" />
        </el-form-item>
        <el-form-item label="经验总结" prop="summary">
          <el-input v-model="form.summary" type="textarea" :rows="4" placeholder="请总结从问题中获得的经验教训、解决方案和改进建议" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入其他相关备注信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button v-if="hasPermission" type="primary" @click="handleSubmit" :loading="submitLoading">确认</el-button>
      </template>
    </el-dialog>

    <!-- 经验总结详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="经验总结详情"
      width="800px"
      align-center
    >
      <div class="experience-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="涉及方面">{{ selectedExperience.aspect }}</el-descriptions-item>
          <el-descriptions-item label="所属项目">{{ selectedExperience.project_id }}</el-descriptions-item>
          <el-descriptions-item label="问题过程" :span="2">
            {{ selectedExperience.discovery_process || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="经验总结" :span="2">
            {{ selectedExperience.summary || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ selectedExperience.remark || '-' }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 经验总结分析 -->
        <div class="detail-content" v-if="selectedExperience.summary">
          <h4>经验总结分析</h4>
          <div class="content-section">
            <h5>问题背景</h5>
            <p>{{ selectedExperience.discovery_process || '暂无描述' }}</p>
          </div>
          
          <div class="content-section">
            <h5>经验教训</h5>
            <p>{{ selectedExperience.summary }}</p>
          </div>
          
          <div class="content-section" v-if="selectedExperience.remark">
            <h5>补充说明</h5>
            <p>{{ selectedExperience.remark }}</p>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Plus, Search, View, Edit, Delete, Refresh } from '@element-plus/icons-vue'
import { 
  getProjectExperienceList, 
  getProjectExperienceListByProjectId,
  createProjectExperience, 
  updateProjectExperience, 
  deleteProjectExperience 
} from '../../api/projectExperience'
import { getProjectList } from '../../api/project'

// 定义props
const props = defineProps({
  projectId: {
    type: String,
    default: ''
  },
  projectData: {
    type: Object,
    default: () => ({})
  }
})

// 获取当前登录用户信息
const currentUser = ref(JSON.parse(localStorage.getItem('user') || '{}'))
const isAdmin = computed(() => currentUser.value.userType === '管理员')

// 检查是否为当前项目的项目经理
const isProjectManager = computed(() => {
  if (!props.projectData || !props.projectData.project_manager) {
    return false
  }
  // 检查当前用户是否为该项目的项目经理
  return currentUser.value.username === props.projectData.project_manager || 
         currentUser.value.userId === props.projectData.project_manager ||
         currentUser.value.id === props.projectData.project_manager
})

// 检查是否有权限操作（只有当前项目的项目经理可以操作）
const hasPermission = computed(() => {
  return isProjectManager.value
})

// 检查是否可以新增和删除（只有当前项目的项目经理可以操作）
const canAdd = computed(() => {
  return isProjectManager.value
})

// 预定义的涉及方面
const predefinedAspects = [
  '需求分析',
  '系统设计',
  '开发实现',
  '测试验证',
  '部署运维',
  '项目管理',
  '团队协作',
  '质量控制',
  '风险管理',
  '成本控制',
  '进度管理',
  '沟通协调',
  '技术选型',
  '架构设计',
  '性能优化',
  '安全防护',
  '用户体验',
  '文档管理'
]

// 响应式数据
const selectedProject = ref('all')
const experienceList = ref([])
const projectList = ref([])
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const detailVisible = ref(false)
const searchKeyword = ref('')
const filterAspect = ref('')
const filterDateRange = ref([])
const formRef = ref()
const selectedExperience = ref({})

// 分页数据
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const form = ref({
  id: null,
  project_id: '',
  aspect: '',
  discovery_process: '',
  summary: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  project_id: [{ required: true, message: '请选择所属项目', trigger: 'change' }],
  aspect: [{ required: true, message: '请输入涉及方面', trigger: 'blur' }],
  discovery_process: [{ required: true, message: '请输入问题过程', trigger: 'blur' }],
  summary: [{ required: true, message: '请输入经验总结', trigger: 'blur' }]
}

// 涉及方面选项
const aspectOptions = computed(() => {
  const options = new Set()
  experienceList.value.forEach(exp => {
    if (exp.aspect) {
      options.add(exp.aspect)
    }
  })
  return Array.from(options)
})

// 过滤后的经验总结列表
const filteredExperienceList = computed(() => {
  let filtered = experienceList.value
  
  // 根据搜索关键词过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(item => 
      item.aspect?.toLowerCase().includes(keyword) ||
      item.summary?.toLowerCase().includes(keyword) ||
      item.discovery_process?.toLowerCase().includes(keyword) ||
      item.remark?.toLowerCase().includes(keyword)
    )
  }
  
  // 根据涉及方面过滤
  if (filterAspect.value) {
    filtered = filtered.filter(item => item.aspect === filterAspect.value)
  }
  
  return filtered
})

// 分页后的经验总结列表
const paginatedExperienceList = computed(() => {
  const start = (pagination.value.page - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return filteredExperienceList.value.slice(start, end)
})

// 经验总结统计数据
const experienceStats = computed(() => {
  const total = filteredExperienceList.value.length
  const aspects = new Set(filteredExperienceList.value.map(item => item.aspect)).size
  const projects = new Set(filteredExperienceList.value.map(item => item.project_id)).size
  
  const currentMonth = new Date().getMonth()
  const currentYear = new Date().getFullYear()
  const thisMonth = filteredExperienceList.value.filter(item => {
    // 这里可以根据实际需要调整统计逻辑
    return true // 暂时返回所有数据
  }).length
  
  return { total, aspects, projects, thisMonth }
})

// 获取项目列表
async function loadProjectList() {
  try {
    const response = await getProjectList({ page: 1, pageSize: 1000 })
    if (response.data && response.data.data) {
      projectList.value = response.data.data
    } else if (Array.isArray(response.data)) {
      projectList.value = response.data
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
    ElMessage.error('获取项目列表失败')
  }
}

// 加载项目经验总结列表
async function loadProjectExperience() {
  loading.value = true
  try {
    const currentProjectId = props.projectData.project_id || props.projectId || selectedProject.value
    
    if (currentProjectId && currentProjectId !== 'all') {
      console.log('加载项目经验总结，项目ID:', currentProjectId)
      
      const res = await getProjectExperienceListByProjectId(currentProjectId)
      const allExperiences = Array.isArray(res) ? res : []
      
      // 过滤当前项目的数据
      experienceList.value = allExperiences.filter(item => item.project_id === currentProjectId)
      console.log('当前项目经验总结数量:', experienceList.value.length)
      console.log('经验总结数据:', experienceList.value)
    } else {
      // 加载所有经验总结
      const response = await getProjectExperienceList({ page: 1, pageSize: 1000 })
      if (response.data && response.data.data) {
        experienceList.value = response.data.data
      } else if (Array.isArray(response.data)) {
        experienceList.value = response.data
      } else {
        experienceList.value = []
      }
    }
  } catch (error) {
    ElMessage.error('加载项目经验总结失败')
    console.error('加载项目经验总结失败:', error)
    experienceList.value = []
  } finally {
    loading.value = false
  }
}

// 项目选择变化
function handleProjectChange() {
  loadProjectExperience()
}

// 刷新数据
function refreshData() {
  loadProjectExperience()
}

// 打开对话框
function openDialog(experience = null) {
  if (experience) {
    form.value = { ...experience }
  } else {
    form.value = {
      id: null,
      project_id: props.projectData.project_id || props.projectId || (selectedProject.value === 'all' ? '' : selectedProject.value),
      aspect: predefinedAspects[0] || '',
      discovery_process: '',
      summary: '',
      remark: ''
    }
  }
  dialogVisible.value = true
}

// 提交表单
async function handleSubmit() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (form.value.id) {
      // 更新
      await updateProjectExperience(form.value.id, form.value)
      ElMessage.success('经验总结更新成功')
    } else {
      // 创建
      await createProjectExperience(form.value)
      ElMessage.success('经验总结创建成功')
    }
    
    dialogVisible.value = false
    loadProjectExperience()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    submitLoading.value = false
  }
}

// 查看详情
function viewDetail(experience) {
  selectedExperience.value = experience
  detailVisible.value = true
}

// 删除经验总结
async function handleDelete(id) {
  try {
    await ElMessageBox.confirm('确定要删除这个经验总结吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteProjectExperience(id)
    ElMessage.success('删除成功')
    loadProjectExperience()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

// 分页处理
function handleSizeChange(newSize) {
  pagination.value.pageSize = newSize
  pagination.value.page = 1
}

function handleCurrentChange(newPage) {
  pagination.value.page = newPage
}

// 监听项目数据变化
watch(() => props.projectData, (newProjectData) => {
  if (newProjectData && newProjectData.project_id) {
    if (dialogVisible.value && !form.value.project_id) {
      form.value.project_id = newProjectData.project_id
    }
    loadProjectExperience()
  }
}, { deep: true })

// 监听项目ID变化
watch(() => props.projectId, (newProjectId) => {
  if (newProjectId) {
    console.log('项目ID变化，重新加载项目经验总结:', newProjectId)
    loadProjectExperience()
  }
})

// 页面初始化
onMounted(async () => {
  try {
    await loadProjectList()
    await loadProjectExperience()
  } catch (error) {
    console.error('项目经验总结页面初始化失败:', error)
  }
})
</script>

<style scoped>
.experience-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.experience-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.title-section {
  flex: 1;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-icon {
  font-size: 24px;
  color: #909399;
}

.description {
  margin: 0;
  font-size: 14px;
  color: #909399;
  line-height: 1.5;
}

.create-btn, .refresh-btn {
  padding: 12px 20px;
  font-weight: 500;
  border-radius: 8px;
}

.project-selector {
  margin-bottom: 20px;
}

.filter-section {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  flex: 1;
  max-width: 300px;
}

.experience-table {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.pagination-section {
  margin-bottom: 30px;
  display: flex;
  justify-content: center;
}

.experience-stats {
  margin-top: 20px;
}

.stat-card {
  text-align: center;
  border-radius: 8px;
}

.stat-content {
  padding: 20px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.experience-detail {
  padding: 20px 0;
}

.detail-content {
  margin-top: 20px;
}

.detail-content h4 {
  margin-bottom: 16px;
  color: #303133;
}

.content-section {
  margin-bottom: 20px;
}

.content-section h5 {
  margin-bottom: 8px;
  color: #606266;
  font-weight: 600;
}

.content-section p {
  margin: 4px 0;
  color: #606266;
  line-height: 1.6;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background: #f5f7fa !important;
  font-weight: 600;
}
</style> 